package com.zh.ssoclient.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 配置请求授权规则
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/", "/error", "/login", "/css/**", "/js/**").permitAll()
                        .anyRequest().authenticated()
                )

                // 配置OAuth2登录 - 使用标准配置
                .oauth2Login(oauth2 -> oauth2
                        // 不直接设置登录页为授权端点，让Spring Security自动处理

                         // 设置登录页为Spring Security默认的OAuth2登录页
//                         .loginPage("/oauth2/authorization/freechat")

                         // 这样可以保留原始请求中的所有参数
                        .defaultSuccessUrl("/home")
                        // 登录失败处理
//                        .failureUrl("/?login_error=true")
                        // 使用默认的OidcUserService
                        .userInfoEndpoint(userInfo -> userInfo.oidcUserService(new OidcUserService()))
                )
                // 配置退出登录
                .logout(logout -> logout
                        .logoutSuccessUrl("/")
                        .permitAll()
                )
                .csrf(csrf -> csrf.disable());

        return http.build();
    }

    // 配置OAuth2授权客户端管理器
    @Bean
    public DefaultOAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository) {
        return new DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientRepository);
    }
}
